import { getJwt, getUserCache } from "@/utils/storage";
import { ref, Ref } from "vue";
import { useRoute } from "vue-router";
import { comment } from "@/api/comment.api";
import { toast } from "@/hooks/useToast";
export const useComment = (): {
  commentText: Ref<string>;
  onComment: (
    rootId: string,
    toCommentId?: string,
    toCommentUserId?: string
  ) => Promise<boolean>;
} => {
  const commentText = ref("");
  const route = useRoute();
  const onComment = async (
    rootId: string,
    toCommentId?: string,
    toCommentUserId?: string
  ): Promise<boolean> => {
    const jwt = getJwt();
    const user = getUserCache();
    const articleId = route.query.id as string;
    if (!(jwt && user && user.id && articleId)) {
      toast("请先登陆!");
      return false;
    }
    if (!commentText.value) {
      toast("评论内容不能为空!");
    }
    const params = {
      rootId,
      content: commentText.value,
      toCommentId: toCommentId || "-1",
      toCommentUserId: toCommentUserId || "-1",
      type: "0",
      articleId,
    };
    const res = await comment(params);
    if (res.code == 200) {
      commentText.value = "";
      return true;
    }
    return false;
  };

  return {
    commentText,
    onComment,
  };
};
